use zmath::{Vec2, Vec4};

use zert::glutils::*;
use zert::graphics;
use zert::Camera2D;
use zert::shaders::{SIMPLE_TEX_VERTEX_SHADER_SRC, TEX_FRAGMENT_SHADER_SRC};

fn main() {
    use glfw::{ Action, Context, Key, WindowMode };

    let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS)
        .expect("Failed to init glfw");

    let (mut window, events) = glfw.create_window(800, 600, "Draw Sprite", WindowMode::Windowed)
        .unwrap();

    window.make_current();

    zert::load(|s| window.get_proc_address(s));

    window.set_all_polling(true);

    let texture = {
        let img = image::open("images/test.png").unwrap().into_rgba();
        let (width, height) = img.dimensions();

        graphics::Texture::with_pixels(width, height, graphics::TextureFormat::RGBA, &img.into_raw())
    };

    let mut sbatch = graphics::SpriteBatcher::new((800.0, 600.0), texture.clone());

    let mut rbatch = graphics::RectBatcher::new((800.0, 600.0));

    let mut camera = Camera2D::new();

    let fb = graphics::FrameBuffer::new(Vec2(800.0, 600.0));
    let simple_shader = ShaderProgram::from_source(SIMPLE_TEX_VERTEX_SHADER_SRC, TEX_FRAGMENT_SHADER_SRC);

    let mut fbatch = graphics::SpriteBatcher::new((8.0, -6.0), fb.texture());

    let quad = VertexArray::quad(Vec2(1.0, 0.0), Vec2(0.001, 0.001));

    let mut i = 0;

    simple_shader.set_uniform("tex", 1);

    while !window.should_close() {
        glfw.poll_events();
        for (_, event) in glfw::flush_messages(&events) {
            match event {
                glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => {
                    window.set_should_close(true)
                }
                glfw::WindowEvent::MouseButton(glfw::MouseButton::Button1, Action::Press, _) => {
                    i = (i + 1) % 3;
                }
                glfw::WindowEvent::CursorPos(x, y) => {
                    camera.set_position(Vec2(-400.0 + x as f32, 300.0 - y as f32));
                }
                _ => {},
            }
        }

        fb.bind();

        gl_clear_color(1.0, 1.0, 1.0, 1.0);
        gl_clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);



        sbatch.begin();
        sbatch.draw(0.0, 0.0, 384.0, 192.0);
        sbatch.present(Some(&camera));

        rbatch.begin();
        rbatch.draw_rect(0.0, 0.0, 50.0, 50.0, &[Vec4(1.0, 0.0, 0.0, 0.3)]);
        rbatch.present(None);

        fb.unbind();

        gl_clear_color(0.5, 0.5, 0.5, 1.0);
        gl_clear(gl::COLOR_BUFFER_BIT);


        fbatch.shader().set_uniform("modes", i);
        fbatch.begin();
        fbatch.draw(0.0, 0.0, 8.0, 6.0);
        fbatch.present(None);

        window.swap_buffers();
    }
}